using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UI_TreeConnection : MonoBehaviour
{
    [SerializeField] private RectTransform rotatePoint;
    [SerializeField] private RectTransform connectionLength;
    [SerializeField] private RectTransform childNodeConnectionPoint;
    
    //更新当前节点下的分支的旋转和长度
    public void DirectConnection(NodeDirectionType direction, float length,float rotateOffset)
    {
        bool shouldBeActive = direction != NodeDirectionType.None;
        float finalLength = shouldBeActive ? length : 0;
        float angle = GetDirection(direction);
        //更改旋转角度
        rotatePoint.localRotation = Quaternion.Euler(0, 0, angle + rotateOffset);
        //更改长度
        connectionLength.sizeDelta = new Vector2(finalLength, connectionLength.sizeDelta.y);
    }

    public float GetDirection(NodeDirectionType direction)
    {
        switch (direction)
        {
            case NodeDirectionType.Right: return 0f;
            case NodeDirectionType.UpRight: return 45f;
            case NodeDirectionType.Up: return 90f;
            case NodeDirectionType.UpLeft: return 135f;
            case NodeDirectionType.Left: return 180f;
            case NodeDirectionType.DonwRight: return -45f;
            case NodeDirectionType.Down: return -90f;
            case NodeDirectionType.DownLeft: return -135f;
            default: return 0f;
        }
    }
    public Image GetConnectionImage() => connectionLength.GetComponent<Image>();
    //得到下一个节点的连接点，统一为Canvas下的局部坐标
    public Vector2 GetConnectionPoint(RectTransform rect) //传入节点的RectTransform
    {
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            rect.parent as RectTransform, //节点的父级，即Canvas
            childNodeConnectionPoint.position, //子节点的连接点的世界位置，方法内部会自动将其转换为屏幕坐标，再进行后续转换
            null, // 用于转换的摄像机
            out var localPosition // 转换后的本地坐标,即Canvas下的坐标，与当前节点处在同一个本地坐标系下
        );
        return localPosition;
    }
}

public enum NodeDirectionType
{
    None,
    UpLeft,
    Up,
    UpRight,
    Left,
    Right,
    DownLeft,
    Down,
    DonwRight
}
